﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.Text;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
	protected void btnTest_Click(object sender, EventArgs e)
	{
		RegexOptions options = RegexOptions.None;
		if(chkCultureInvariant.Checked)
			options |= RegexOptions.CultureInvariant;
		if(chkExplicitCapture.Checked)
			options |= RegexOptions.ExplicitCapture;
		if(chkIgnoreCase.Checked)
			options |= RegexOptions.IgnoreCase;
		if(chkIgnorePatternWhitespace.Checked)
			options |= RegexOptions.IgnorePatternWhitespace;
		if(chkMultiline.Checked)
			options |= RegexOptions.Multiline;
		if(chkRightToLeft.Checked)
			options |= RegexOptions.RightToLeft;
		if(chkSingleline.Checked)
			options |= RegexOptions.Singleline;

		MatchCollection matches = testRegex(txtRegex.Text, txtText.Text, options);
		string result = generateResult(matches);
		lblResult.Text = result;
	}

	private string generateResult(MatchCollection matches)
	{
		if(matches == null || matches.Count == 0)
		{
			return "<div class=\"no-match\">No matches.</div>";
		}

		StringBuilder sbResult = new StringBuilder();
		for(int i = 0; i < matches.Count; i++)
		{
			if(i % 2 == 0)
				sbResult.Append("<div class=\"result-line-odd\">");
			else
				sbResult.Append("<div class=\"result-line-even\">");

			sbResult.AppendFormat("<h3>Match {0}</h3>", i);

			for(int j = 0; j < matches[i].Groups.Count; j++)
			{
				sbResult.AppendFormat("<h4>Group {0}</h4>", j);

				for(int k = 0; k < matches[i].Groups[j].Captures.Count; k++)
				{
					sbResult.AppendFormat("<h5>Capture {0}</h5>", k);
					sbResult.Append("<table>");
					sbResult.AppendFormat("<tr><th>Index</th><td>{0}</td></tr>", matches[i].Groups[j].Captures[k].Index);
					sbResult.AppendFormat("<tr><th>Length</th><td>{0}</td></tr>", matches[i].Groups[j].Captures[k].Length);
					sbResult.AppendFormat("<tr><th>Value</th><td>{0}</td></tr>", HttpUtility.HtmlEncode(matches[i].Groups[j].Captures[k].Value));
					sbResult.Append("</table>");
				}
			}

			sbResult.Append("</div>");
		}

		return sbResult.ToString();
	}

	private MatchCollection testRegex(string regex, string text, RegexOptions options)
	{
		Regex reg = new Regex(regex, options);
		MatchCollection matches = reg.Matches(text);
		return matches;
	}
}
